using Chaotic.DataBase.DBAccessLibrary.DBAccessLibrary;
using Chaotic.DataBase.DBAccessLibrary.Interface;

namespace Chaotic.DataBase.DBAccessLibrary.Model;

[Serializable]
public class TableEntity : DataBaseEntity
{
	public string PrimaryKeyName { get; set; }

	public IEnumerable<FieldEntity> FieldNodes
	{
		get
		{
			if (ChildNodes.Count == 0)
				return new List<FieldEntity>();
            return ChildNodes[0].ChildNodes.Cast<FieldEntity>();
		}
	}

	public IEnumerable<RelationshipEntity> RelationNodes
    {
        get
        {
            if (ChildNodes.Count == 0)
                return new List<RelationshipEntity>();
            return ChildNodes[1].ChildNodes.Cast<RelationshipEntity>(); 
        }
    }
    

	public IEnumerable<IndexDescriptionEntity> IndexNodes
    {
        get
        {
            if (ChildNodes.Count == 0)
                return new List<IndexDescriptionEntity>();
            return ChildNodes[2].ChildNodes.Cast<IndexDescriptionEntity>(); 
        }
    }
    

	public IEnumerable<string> AddPrimarySql { get; private set; } = new List<string>();

    public TableEntity(string name)
		: base(name)
	{
		base.ImageUrl = "/Images/Tree/table.png"; 
		IGrammar? grammar = DBOperatorFactory.GetGrammar(SysCache.DBConnection);
		if (grammar != null)
			AddPrimarySql = grammar.EditPrimary(this); 
	}

	public string SelectAll()
	{
        IGrammar? grammar = DBOperatorFactory.GetGrammar(SysCache.DBConnection);
        if (grammar != null)
            return grammar.SelectAll(this);
		return string.Empty;
	}

	public string SelectTop()
	{
		if (SysCache.DBConnection != null)
		{
            IGrammar? grammar = DBOperatorFactory.GetGrammar(SysCache.DBConnection);
            if (grammar != null)
                return grammar.SelectTop(this, 100);
		}
		return string.Empty;
	}

	public void Add(FieldEntity? entity)
	{
		if (entity != null)
		{
			ChildNodes[0].ChildNodes.Add(entity);
		}
	}

	public void Remove(FieldEntity? entity)
	{
		if (entity != null)
		{
			ChildNodes[0].ChildNodes.Remove(entity);
		}
	}

	public override DataBaseEntity Copy()
	{
		TableEntity tableEntity = new TableEntity(Name);
		Copy(tableEntity);
		if (ChildNodes.Count > 0)
		{
			foreach (DataBaseEntity childNode in ChildNodes)
			{
                tableEntity.ChildNodes.Add(childNode.Copy());
            }
		}
		return tableEntity;
	}

	public void Commit()
	{
		foreach (FieldEntity fileNode in FieldNodes)
		{
			fileNode.Commit();
		}
	}

	public void RollBack()
	{
		foreach (FieldEntity fileNode in FieldNodes)
		{
			fileNode.RollBack();
		}
	}
}
